﻿using AutoPrint.BJPT.BLL;
using AutoPrint.BJPT.Model;
using AutoPrint.BJPT.Utils;
using HZH_Controls.Controls;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace AutoPrint.BJPT
{
    public partial class Main : Form
    {
        /// <summary>
        /// 界面二维码采集列表数据源
        /// </summary>
        private BindingList<EngineModel> DG_Models = new BindingList<EngineModel>();

        private BindingList<LogModel> LV_Models = new BindingList<LogModel>();

        /// <summary>
        /// OPC客户端实例
        /// </summary>
        private OPCClient Client = new OPCClient();

        /// <summary>
        /// 业务层
        /// </summary>
        private EngineService engineService = new EngineService();

        /// <summary>
        /// 设备编号
        /// </summary>
        private readonly string ASSETNUM = ConfigurationManager.AppSettings["ASSETNUM"];

        /// <summary>
        /// 是否开启监控功能
        /// </summary>
        private bool IsActive = Convert.ToBoolean(Convert.ToInt16(ConfigurationManager.AppSettings["IsActive"]));

        /// <summary>
        /// 是否开启打印功能
        /// </summary>
        private bool IsPrint = Convert.ToBoolean(Convert.ToInt16(ConfigurationManager.AppSettings["IsPrint"]));

        /// <summary>
        /// 打印阀值
        /// </summary>
        private readonly int PrintCount = Convert.ToInt32(ConfigurationManager.AppSettings["PrintCount"]);




        /// <summary>
        /// 主界面加载入口
        /// </summary>
        public Main()
        {
            InitializeComponent();
            DG_EunList.AutoGenerateColumns = false;
            DG_EunList.DataSource = DG_Models;

            //界面初始化+数据绑定
            InitialData();


            Client.StartRun();
            Client.EngineNumChanged += Client_EngineNumChanged;
            ComExcel.Printed += ComExcel_Printed;
        }

        /// <summary>
        /// 打印完成事件响应
        /// </summary>
        /// <param name="sender">ComExcel</param>
        /// <param name="e"></param>
        private void ComExcel_Printed(object sender, EventArgs e)
        {
            //1.更新打印结果
            var printer = sender as ComExcel;
            AddLV_Log($"{DateTime.Now.ToString("MM-dd HH:mm:ss:fff")} 完成打印,打印{printer.PrintCount}项数据.");

            //2.更新数据库
            var updated = engineService.UpdatePrint(printer.listEun);
            AddLV_Log($"{DateTime.Now.ToString("MM-dd HH:mm:ss:fff")} 完成数据库更新,更新{updated}项数据.");

            //3.清空列表
            DG_Models.Clear();

        }

        /// <summary>
        /// 初始化各个UI控件
        /// </summary>
        private void InitialData()
        {
            var last_data = engineService.LoadLastData();

            foreach (var item in last_data)
            {
                DG_Models.Add(new EngineModel
                {
                    No = DG_Models.Count+1,
                    Date = item.CREATEDATE.ToString("yyyy-MM-dd"),
                    Time = item.CREATEDATE.ToString("HH:mm:ss"),
                    Eun = item.EUN,
                    ID=item.ID
                });
            }



            LB_tgt_Count.Text = PrintCount.ToString().PadLeft(2,'0');//打印阀值
            CB_Active.Checked = IsActive;//监控使能
            CB_Print.Checked = IsPrint;//打印使能

        }



        /// <summary>
        /// 有符合要求的二维码出现
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Client_EngineNumChanged(object sender, EventArgs e)
        {
            try
            {
                var OPCData = sender as OPCClient;

                //监控无使能，则直接返回
                if (IsActive == false)
                {
                    return;
                }
                //1.插入数据库
                ENGINE engine = new ENGINE
                {
                    ASSETNUM = ASSETNUM,
                    CLIENTHANDLE = 1000,
                    TIMESTAMP = OPCData.TimeStamp,
                    DATE = Convert.ToInt32(DateTime.Now.ToString("yyyyMMdd")),
                    EUN = OPCData.ItemValue,
                    PRINTED = "否"
                };
                var id = engineService.Insert(engine);


                //2.更新UI
                UpdateUI(OPCData.ItemValue, id);


                //3.触发打印
                if (DG_Models.Count >= PrintCount)
                {
                    ComExcel excel = new ComExcel();
                    excel.PrintData(DG_Models.ToList(), IsPrint, ASSETNUM);
                }

            }
            catch (Exception ex)
            {

                MessageBox.Show("数据刷新失败,错误信息:" + ex.Message);
            }
        }


        /// <summary>
        /// 根据抓取二维码更新界面UI控件
        /// </summary>
        /// <param name="OPCData">OPC数据</param>
        /// <param name="id">输入数据库返回ID</param>
        private void UpdateUI(string OPCData, long id)
        {
            DG_EunList.Invoke(new Action(() =>
            {

                //2.1更新列表
                EngineModel model = new EngineModel
                {
                    No = DG_Models.Count+1,
                    Date = DateTime.Now.ToString("yyyy-MM-dd"),
                    Time = DateTime.Now.ToString("HH:mm:ss"),
                    Eun = OPCData,
                    ID=id
                };
                DG_Models.Add(model);

                //2.2更新Label
                //已采集标签
                LB_cur_Count.Text = DG_Models.Count.ToString().PadLeft(2, '0');
                LB_last_Date.Text = DateTime.Now.ToString("yyyy-MM-dd");
                LB_last_Time.Text = DateTime.Now.ToString("HH:mm:ss");
                LB_cur_Eun.Text = OPCData.PadLeft(14, '-');

                AddLV_Log($"{DateTime.Now.ToString("MM-dd HH:mm:ss:fff")} 监控到过线工件,工件编号[{OPCData}].");
                //始终滚动到最后一行
                DG_EunList.FirstDisplayedCell = DG_EunList.Rows[DG_EunList.Rows.Count - 1].Cells[0];
            }));
        }

        /// <summary>
        /// 添加数据至ListBox控件[LBX_Log]
        /// </summary>
        /// <param name="v"></param>
        private void AddLV_Log(string content)
        {
            LBX_Log.Items.Add(content);
            if (LBX_Log.Items.Count > 50)
            {
                LBX_Log.Items.RemoveAt(0);
            }
            LBX_Log.SelectedIndex = LBX_Log.Items.Count - 1;
        }

        /// <summary>
        /// 鼠标移动至按钮事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Btn_His_MouseMove(object sender, MouseEventArgs e)
        {
            Btn_His.BackColor = Color.FromArgb(149, 165, 166);
        }

        /// <summary>
        /// 鼠标移出按钮事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Btn_His_MouseLeave(object sender, EventArgs e)
        {
            Btn_His.BackColor = Color.FromArgb(48, 51, 107);
        }

        private void Main_FormClosing(object sender, FormClosingEventArgs e)
        {
            Client.Disconnect();
        }

        /// <summary>
        /// 删除按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Btn_Del_Click(object sender, EventArgs e)
        {
            var index = DG_EunList.CurrentRow.Index;
            var data = DG_Models[index];
            try
            {
                ///数据库删除
                ENGINE engine = new ENGINE
                {
                    ID = (int)data.ID
                };
                //弹窗确认
                if (MessageBox.Show($"确认删除二维码[{data.Eun}]？", "此删除不可恢复", MessageBoxButtons.YesNo) == DialogResult.Yes)
                {
                    var result = engineService.Delete(engine);
                    if (result == true)
                    {
                        ///列表删除
                        DG_Models.RemoveAt(index);
                        //刷新序号列
                        for (int i = 0; i < DG_Models.Count; i++)
                        {
                            DG_Models[i].No = i + 1;
                        }

                        AddLV_Log($"{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")} 删除二维码[{data.Eun}]成功");
                    }
                    else
                    {
                        AddLV_Log($"{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")} 数据库无二维码[{data.Eun}],删除失败");
                        MessageBox.Show("未发现需要删除的二维码,请联系管理员");
                    }
                }

            }
            catch (Exception ex)
            {
                AddLV_Log($"{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")} 删除二维码[{data.Eun}]失败");
                MessageBox.Show("删除失败,错误信息:" + ex.Message);
            }
        }

        private void Btn_His_Click(object sender, EventArgs e)
        {
            new History().ShowDialog();
        }


        /// <summary>
        /// 监控使能开关
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void CB_Active_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show($"确认切换监控状态？", "关闭后无法采集二维码信息", MessageBoxButtons.YesNo) == DialogResult.Yes)
            {
                CB_Active.Checked = !CB_Active.Checked;
                IsActive = !IsActive;
            }
        }

        /// <summary>
        /// 打印使能开关
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void CB_Print_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show($"确认切换打印状态？", "关闭后无法自动打印", MessageBoxButtons.YesNo) == DialogResult.Yes)
            {
                CB_Print.Checked = !CB_Print.Checked;
                IsPrint = !IsPrint;
            }
        }

        /// <summary>
        /// 手动打印当前列表
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button1_Click(object sender, EventArgs e)
        {
            ComExcel excel = new ComExcel();
            excel.PrintData(DG_Models.ToList(), IsPrint, ASSETNUM);
        }

        /// <summary>
        /// 窗口显示完成事件,滚动列表
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Main_Shown(object sender, EventArgs e)
        {
            //始终滚动到最后一行
            if (DG_EunList.Rows.Count > 0)
            {
                DG_EunList.FirstDisplayedCell = DG_EunList.Rows[DG_EunList.Rows.Count - 1].Cells[0];

            }
        }
    }
}
